<?php
namespace catchAdmin\externalGoods\model;

use catcher\base\CatchModel;
use think\Exception;
use think\facade\Db;

class Category extends CatchModel
{

//    protected $name = 'db_syst_sync_goods_category';
    protected $name = 'db_syst_sync_goods_category_0428';
    protected $field = [
        'id',
        'hn_cate_id',
        'hth_cate_id',
        'xy_cate_id',
        'pid',
        'level',
        'name',
        'image',
        'sort',
        'created_at',
        'updated_at',
        'deleted_at',
        'tenant_id',
        'creator_id'
    ];

    public function getList($tenant_id=0)
    {
        $where = [];
        if($tenant_id !== 0){
            $where[]=['tenant_id','=',$tenant_id];
        }

        return $this
            ->field('id,pid,level,name')
//            ->withoutField(['updated_at','created_at','deleted_at','tenant_id','creator_id','supplier_id'], true)
            ->catchSearch()
            ->where($where)
            ->order($this->aliasField('id'), 'asc')
            ->select()
            ->toArray();
    }

    public function checkUnique($where, $id = 0, $pk = 'id')
    {
        try {
            if (empty($id)) {
                $has = $this->field($pk)->where($where)->find();
            } else {
                $has = $this->field($pk)->where($where)->where($pk, '<>', $id)->find();
            }
        } catch (\Exception $e) {
            throw new Exception($e->getMessage());
        }

        return $has;
    }

    //分类层级
    public function getCateIdArrAttr()
    {
        $fullName = [$this->getData('id')];
        $parent = $this->parentCategory;
        while ($parent) {
            array_unshift($fullName,$parent->getData('id'));
            $parent = $parent->parentCategory;
        }
        return $fullName;
    }

    public function parentCategory()
    {
        return $this->belongsTo(Category::class, 'pid','id');
    }

    //分类层级
    public function getCateNameArrAttr()
    {
        $fullName = [$this->getData('name')];
        $parent = $this->parentCategory;
        while ($parent) {
            array_unshift($fullName,$parent->getData('name'));
            $parent = $parent->parentCategory;
        }
        return $fullName;
    }
}
